// shim window.console.log to avoid errors in IE.
// this is not a complete shim - just one for the most common .log function that might be left behind by a debugging session.
if (!window.console) {
  window.console = {
    log : function(msg){
    }
  };
}
(function(){

var $$;

/**
 *
 * @desc Replace matching elements with a flash movie.
 * @author Luke Lutman
 * @version 1.0.1
 *
 * @name flash
 * @param Hash htmlOptions Options for the embed/object tag.
 * @param Hash pluginOptions Options for detecting/updating the Flash plugin (optional).
 * @param Function replace Custom block called for each matched element if flash is installed (optional).
 * @param Function update Custom block called for each matched if flash isn't installed (optional).
 * @type jQuery
 *
 * @cat plugins/flash
 *
 * @example $('#hello').flash({ src: 'hello.swf' });
 * @desc Embed a Flash movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { version: 8 });
 * @desc Embed a Flash 8 movie.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { expressInstall: true });
 * @desc Embed a Flash movie using Express Install if flash isn't installed.
 *
 * @example $('#hello').flash({ src: 'hello.swf' }, { update: false });
 * @desc Embed a Flash movie, don't show an update message if Flash isn't installed.
 *
**/
$$ = jQuery.fn.flash = function(htmlOptions, pluginOptions, replace, update) {

  // Set the default block.
  var block = replace || $$.replace;

  // Merge the default and passed plugin options.
  pluginOptions = $$.copy($$.pluginOptions, pluginOptions);

  // Detect Flash.
  if(!$$.hasFlash(pluginOptions.version)) {
    // Use Express Install (if specified and Flash plugin 6,0,65 or higher is installed).
    if(pluginOptions.expressInstall && $$.hasFlash(6,0,65)) {
      // Add the necessary flashvars (merged later).
      var expressInstallOptions = {
        flashvars: {
          MMredirectURL: location,
          MMplayerType: 'PlugIn',
          MMdoctitle: jQuery('title').text()
        }
      };
    // Ask the user to update (if specified).
    } else if (pluginOptions.update) {
      // Change the block to insert the update message instead of the flash movie.
      block = update || $$.update;
    // Fail
    } else {
      // The required version of flash isn't installed.
      // Express Install is turned off, or flash 6,0,65 isn't installed.
      // Update is turned off.
      // Return without doing anything.
      return this;
    }
  }

  // Merge the default, express install and passed html options.
  htmlOptions = $$.copy($$.htmlOptions, expressInstallOptions, htmlOptions);

  // Invoke $block (with a copy of the merged html options) for each element.
  return this.each(function(){
    block.call(this, $$.copy(htmlOptions));
  });

};
/**
 *
 * @name flash.copy
 * @desc Copy an arbitrary number of objects into a new object.
 * @type Object
 *
 * @example $$.copy({ foo: 1 }, { bar: 2 });
 * @result { foo: 1, bar: 2 };
 *
**/
$$.copy = function() {
  var options = {}, flashvars = {};
  for(var i = 0; i < arguments.length; i++) {
    var arg = arguments[i];
    if(arg == undefined) continue;
    jQuery.extend(options, arg);
    // don't clobber one flash vars object with another
    // merge them instead
    if(arg.flashvars == undefined) continue;
    jQuery.extend(flashvars, arg.flashvars);
  }
  options.flashvars = flashvars;
  return options;
};
/*
 * @name flash.hasFlash
 * @desc Check if a specific version of the Flash plugin is installed
 * @type Boolean
 *
**/
$$.hasFlash = function() {
  // look for a flag in the query string to bypass flash detection
  if(/hasFlash\=true/.test(location)) return true;
  if(/hasFlash\=false/.test(location)) return false;
  var pv = $$.hasFlash.playerVersion().match(/\d+/g);
  var rv = String([arguments[0], arguments[1], arguments[2]]).match(/\d+/g) || String($$.pluginOptions.version).match(/\d+/g);
  for(var i = 0; i < 3; i++) {
    pv[i] = parseInt(pv[i] || 0);
    rv[i] = parseInt(rv[i] || 0);
    // player is less than required
    if(pv[i] < rv[i]) return false;
    // player is greater than required
    if(pv[i] > rv[i]) return true;
  }
  // major version, minor version and revision match exactly
  return true;
};
/**
 *
 * @name flash.hasFlash.playerVersion
 * @desc Get the version of the installed Flash plugin.
 * @type String
 *
**/
$$.hasFlash.playerVersion = function() {
  // ie
  try {
    try {
      // avoid fp6 minor version lookup issues
      // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
      var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
      try { axo.AllowScriptAccess = 'always';  }
      catch(e) { return '6,0,0'; }
    } catch(e) {}
    return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
  // other browsers
  } catch(e) {
    try {
      if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
        return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
      }
    } catch(e) {}
  }
  return '0,0,0';
};
/**
 *
 * @name flash.htmlOptions
 * @desc The default set of options for the object or embed tag.
 *
**/
$$.htmlOptions = {
  height: 240,
  flashvars: {},
  pluginspage: 'http://www.adobe.com/go/getflashplayer',
  src: '#',
  type: 'application/x-shockwave-flash',
  width: 320
};
/**
 *
 * @name flash.pluginOptions
 * @desc The default set of options for checking/updating the flash Plugin.
 *
**/
$$.pluginOptions = {
  expressInstall: false,
  update: true,
  version: '6.0.65'
};
/**
 *
 * @name flash.replace
 * @desc The default method for replacing an element with a Flash movie.
 *
**/
$$.replace = function(htmlOptions) {
  this.innerHTML = '<div class="alt">'+this.innerHTML+'</div>';
  jQuery(this)
    .addClass('flash-replaced')
    .prepend($$.transform(htmlOptions));
};
/**
 *
 * @name flash.update
 * @desc The default method for replacing an element with an update message.
 *
**/
$$.update = function(htmlOptions) {
  var url = String(location).split('?');
  url.splice(1,0,'?hasFlash=true&');
  url = url.join('');
  var msg = '<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';
  this.innerHTML = '<span class="alt">'+this.innerHTML+'</span>';
  jQuery(this)
    .addClass('flash-update')
    .prepend(msg);
};
/**
 *
 * @desc Convert a hash of html options to a string of attributes, using Function.apply().
 * @example toAttributeString.apply(htmlOptions)
 * @result foo="bar" foo="bar"
 *
**/
function toAttributeString() {
  var s = '';
  for(var key in this)
    if(typeof this[key] != 'function')
      s += key+'="'+this[key]+'" ';
  return s;
};
/**
 *
 * @desc Convert a hash of flashvars to a url-encoded string, using Function.apply().
 * @example toFlashvarsString.apply(flashvarsObject)
 * @result foo=bar&foo=bar
 *
**/
function toFlashvarsString() {
  var s = '';
  for(var key in this)
    if(typeof this[key] != 'function')
      s += key+'='+encodeURIComponent(this[key])+'&';
  return s.replace(/&$/, '');
};
/**
 *
 * @name flash.transform
 * @desc Transform a set of html options into an embed tag.
 * @type String
 *
 * @example $$.transform(htmlOptions)
 * @result <embed src="foo.swf" ... />
 *
 * Note: The embed tag is NOT standards-compliant, but it
 * works in all current browsers. flash.transform can be
 * overwritten with a custom function to generate more
 * standards-compliant markup.
 *
**/
$$.transform = function(htmlOptions) {
  htmlOptions.toString = toAttributeString;
  if(htmlOptions.flashvars) htmlOptions.flashvars.toString = toFlashvarsString;
  return '<embed ' + String(htmlOptions) + '/>';
};

/**
 *
 * Flash Player 9 Fix (http://blog.deconcept.com/2006/07/28/swfobject-143-released/)
 *
**/
if (window.attachEvent) {
  window.attachEvent("onbeforeunload", function(){
    __flash_unloadHandler = function() {};
    __flash_savedUnloadHandler = function() {};
  });
}

})();

//***********************************************
//  rbiller code starts here
//
//***********************************************

var lang = window.rbiller.lang.addons;

function calcMinToppings(){


  var min_toppings = $('#min_option_num').val();
  var current_toppings = $('#con_min_option_num').val();


  if( min_toppings != "" ){


     $.ajax({
    url: "ajax.php?function=count-min-toppings&t="  + new Date().getTime(),
     data: $('#itemform').serialize(),
     success: function(response){


      $('#con_min_option_num').val(response);

       },
     dataType: "html"
     });

  }

}
function Dialog(d,w,h){
  var min_toppings,
      current_toppings,
      buttons;
  min_toppings = $('#min_option_num').val();
  current_toppings = $('#con_min_option_num').val()

  if((min_toppings != "" && min_toppings != 1) && current_toppings != min_toppings){
    alert(lang.must_pick + " " + min_toppings )
  } else {

  $.ajax({
      url: "ajax.php?function=add-post",
      data: $('#itemform').serialize(),
      success: function(response){
         $("#message").html(response);
         window.setTimeout(getcart,1000);// small delay before refreshing cart.
      },
      dataType: "html"
    });

  buttons = {}
  buttons[lang.checkout_button] = function(){
      $( this ).dialog( "close" );
      window.location = "index.php?act=checkout"
    };

  buttons[lang.continue_button] = function(){
      $( this ).dialog( "close" );
    };

  $( d ).dialog({
      width: w,
      height: h,
      buttons: buttons
    });


  }
  return false;
}

function toggle(a){

   $(a).slideToggle("fast");

}
function show(div){
  $('.error').hide()
  $(div).show();

}
function hide(div){
  $('.error').hide()
  $(div).hide();

}

function showhide(divin,divout){
    $('.error').hide()
  $(divout).fadeOut();
  $(divin).slideDown();
}

function postToAjax(formname,messageContainerId,posturl){
  $.ajax({
    type: "POST",
    url:  posturl,
    data:  $('#' + formname).serialize(),
    success: function(msg){
      $('#' + messageContainerId).empty();
      $('#' + messageContainerId).append( msg);
    }
  });

}

function loadToppings(id,price,toppings_price,pizza_size){

  $('#pizza_price').empty();
  $('#price_input').empty();
  $('#toppings_price').empty();
  $('#pizza_size').empty();
  $.ajax({
    type: "POST",
    url:  'ajax.php?function=toppings&id=' + id +'&t='  + new Date().getTime(),
    data:  'id=' + id,
    success: function(msg){
      $('#toppings').html( msg);
    }
  });

  $('#pizza_price').text(price);
  $('#price_input').val(price);
  $('#pizza_size').val(pizza_size);
  $('#toppings_price').val(toppings_price);
  $('#pizza_footer').show();
  $('#pizza_header').html(lang.choose_base_toppings + ' <b>' + pizza_size+ '</b>');
  $('#pizza_header').highlightFade('#7bff58');
  $('#pizza_price').highlightFade('#7bff58');
}

function chooseArea(area){

  var topping = $('#current_topping').val();
  if(area == 'Remove'){
    $("." + topping).attr('checked',false);
  } else {
    $("." + topping).val(topping +':' + area);
    $("." + topping).attr('checked',true);
  }

  $("#toppings_pop").dialog("close");
  calculatePizza();
}

function toppingArea(topping){
  $('#current_topping').val(topping);
  var max_toppings = $('#max_toppings').val();

  if($(".toppings_list:checkbox:checked").length > max_toppings){
    $("." + topping).attr('checked',false);
    alert(lang.max_toppings_warning.replace("{max_toppings}", max_toppings));
  }else{
    if($('#half').val() == 0){
      calculatePizza();
    }else{
      $("." + topping).attr('checked',false);
      $( "#toppings_pop" ).dialog({
              height: 200,
              width: 650
      });
    }
  }

}

function calculatePizza(){

  $.ajax({
    type: "POST",
    url:  'ajax.php?function=calculate-pizza&t='  + new Date().getTime(),
    data:  $('#pizzaform').serialize(),
    success: function(msg){
      $('#pizza_price').html(msg);
    }
  });

  $('#pizza_price').highlightFade('#7bff58')
}

function explodeArray(item,delimiter) {
  tempArray=new Array(1);
  var Count=0;
  var tempString=new String(item);

  while (tempString.indexOf(delimiter)>0) {
    tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
    tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1);
    Count=Count+1
  }

  tempArray[Count]=tempString;
  return tempArray;
}



function changeBase(base){

  $('#selected_base').val(base);

}

function calculateBase(){
  var base7 = $('#7base').val();
  var base9 = $('#9base').val();
  var base12 = $('#12base').val();
  var base16 = $('#16base').val();

  var base7a = base7.split('|');
  var base9a = base9.split('|');
  var base12a = base12.split('|');
  var base16a = base16.split('|');

  var base_cat = $('#base_cat').val();
  var price = $('#price').val();

  if(price.indexOf("7 inch") !=-1){

    $('.base_price').text(base7a[0]);
    $('.base_price_input').val(base7a[0]);
    $('.base_price_big').text(base7a[1]);
    $('.base_price_input_big').val(base7a[1]);

  }


  if(price.indexOf("9 inch") !=-1){

    $('.base_price').text(base9a[0]);
    $('.base_price_input').val(base9a[0]);
    $('.base_price_big').text(base9a[1]);
    $('.base_price_input_big').val(base9a[1]);

  }


  if(price.indexOf("12 inch") !=-1){

    $('.base_price').text(base12a[0]);
    $('.base_price_input').val(base12a[0]);
    $('.base_price_big').text(base12a[1]);
    $('.base_price_input_big').val(base12a[1]);

  }


  if(price.indexOf("16 inch") !=-1){

    $('.base_price').text(base16a[0]);
    $('.base_price_input').val(base16a[0]);
    $('.base_price_big').text(base16a[1]);
    $('.base_price_input_big').val(base16a[1]);

  }
}

function getselectedSize($price){
  var split = $price.val().split('|');
  return {
    type: split[0],
    price: parseFloat(split[1])
  }
}

function calculateItem(){
  var $form = $('#itemform'),
      $basePrice = $('#price', $form),
      selectedSize = getselectedSize($basePrice),
      quantity = $('#quantity', $form).val(),
      $optionSets = $('.option_set'),
      optionsTotalCents = 0,
      optionsTotalDollars = 0,
      $options,
      totalPrice;


  // get any drop-downs
  $options = $('#itemform .option_set .options :selected');

  $options.each(function(index){
    var value = $(this).val();
    value = toFloat(value);
    optionsTotalCents += value*100; // convert to cents and total
  });

  // get any checkboxes.
  $checks = $('#itemform .option_set input[type="checkbox"]:checked');

  $checks.each(function(){
    var split = $(this).val().split(','),
        value = 0.0;

    value = toFloat(split[1]);

    optionsTotalCents += value*100; // convert to cents and total
  });

  // get any input boxes
  $inputs = $('#itemform .option_set input[type="text"]');
  $inputs.each(function(){
    var quantity = $(this).val(),
        value = $(this).attr('data-price'),
        price;
    quantity = toInt(quantity);
    value = toFloat(value);
    value = value*100; // convert to cents
    price = quantity * value;

    optionsTotalCents += price; // total

  });


  optionsTotalDollars = optionsTotalCents / 100;

  quantity = toInt(quantity);
  totalPrice = (selectedSize.price + optionsTotalDollars) * quantity;


  $('#final_price').val(totalPrice);
  $('#final_price_type').val(selectedSize.type);
  $('#final_options').val(optionsTotalDollars);
  $('#item_price').text(price_format(totalPrice));

}

function toFloat(val){
  // doesn't handle negative numbers??

  if (val) {
    val = parseFloat(val);
    if (isNaN(val)) {
      val = 0.0;
    }
  } else {
    val = 0.0;
  }

  return val;

}

function toInt(val){
  if (val) {
    val = parseInt(val,10);
    if (isNaN(val)) {
      val = 0;
    }
  } else {
    val = 0;
  }

  return val;
}

function checkSet(max_toppings,id,optionid){
      //alert($(".optionset_"+ id +":checkbox:checked").length);
  if(max_toppings != ""){
    if($(".optionset_"+ id +":checkbox:checked").length > max_toppings){
      $("."+ optionid).attr('checked',false);
      alert("Maximum of " + max_toppings + "!");
    }else{

    }
  }
}

function finishPizza(){
  $('#pizza_header').hide();
  $('#pizza_footer').hide();
  $('#toppings').html('<p style="margin:10px;font-size:1.5em;padding:50px;color:#060">' + lang.added_to_cart + '</p>');
}

function transferto(from,to){
  $(from).effect("transfer", { to: to }, 300);
  $(to).effect("bounce", { easing: "linear", times: 1 }, 300);
}

function appendtext(text,divclass){
  $("."+divclass).empty();
  $("."+divclass).append(document.createTextNode(text));
}

function insertField(divclass,text){
  $("."+divclass).attr("value", text);
}

function calcDelivery(price,delivery_time,pickup_time){
  var selectedDel = $("#delivery").val();
  if(selectedDel == 'Yes'){
    window.location = "index.php?act=checkout&d=1"  ;
  }else{
    window.location = "index.php?act=checkout&d=0"  ;
  }

}


function calcDeliverySelect(){
  var selectedDel, field, total;

  selectedDel = $("#delivery").val();
  if(selectedDel == 'Yes'){
    $('#deliver_select').show();
  } else {
    $('#deliver_select').hide();
    $("#deliveryfee").hide();
    field = $('#delivery_zone');
    field.val($('option:first', field).val());

    total = parseFloat($("#totalprice_before").val()).toFixed(2);
    $("#totalprice").val(total);
    $("#changeprice").text(lang.currency_symbol + total);

  }

}



function calcDeliveryZone(delivery_time, pickup_time){
  var selectedDel, price, total;

  selectedDel = $("#delivery_zone").val();
  price = selectedDel;
  //alert(selectedDel);

  if(selectedDel != ''){
    appendtext(lang.what_time_delivered_question, 'changeme');
    insertField('changemefield', delivery_time );
    $("#deliveryfee").show();
    $("#deliveryfee").text(lang.delivery_fee_label + ' ' + lang.currency_symbol + price);

    total = parseFloat($("#totalprice_before").val()) + parseFloat(price);
    total = total.toFixed(2);
    $("#totalprice").val(total);
    $("#changeprice").text(lang.currency_symbol + total);

  }

}

function addDelivery(price){
  var total;
  appendtext(lang.what_time_delivered_question,'changeme');
  insertField('changemefield','40 ' + lang.minutes);
  $("#deliveryfee").show();


  total = parseFloat($("#totalprice").val()) + parseFloat(price);
  total = total.toFixed(2);
  $("#totalprice").val(total);
  $("#changeprice").text('$' + total);

}

function removeDelivery(price){
  var total;
  appendtext(addons.what_time_order_ready_question,'changeme');
  insertField('changemefield','15 ' + lang.minutes);
  $("#deliveryfee").hide();

  total = (parseFloat($("#totalprice").val()) - parseFloat(price)).toFixed(2);

  $("#totalprice").val(total);
  $("#changeprice").text(lang.currency_symbol + total);

}



function addItem(){
  return false;
}

function refreshCart() {
  var url = "ajax.php?function=cart&" + "&ms=" + new Date().getTime();
  $("#cart").load(url);
}

//setInterval(refreshCart,5000);

// custom functions
function getcart() {
  var url = "ajax.php?function=cart&" + "ms=" + new Date().getTime();
  $("div#cart").load(url);
}


function is_int(value){
  if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
      return true;
  } else {
      return false;
  }
}

function emptyCart(){
  var url = "ajax.php?function=empty&" + "ms=" + new Date().getTime();
  $("#message").load(url);
  getcart();
}

function setupValidation(){

  $('.validatenum').bind('keyup', function() {

    if( is_int($(this).val()) == false &&  $(this).val() != ""  &&  $(this).val() != "0" ){
          $(this).val('1');
    }else{
      if(($(this).val() < 1 || $(this).val() != Math.round(i) )  &&  $(this).val() != "" &&  $(this).val() != "0" ){
        $(this).val('1');
      }
    }
  });

  $("#loginForm").validate();
  $("#loginForm2").validate();
  $("#passwordForm").validate();
  $("#regForm").validate({
    rules:{
      email:'required',
      confirmemail:{
        equalTo:"#email1"
      }
    }
  });

}

function deleteItem(link,itemid,pid){
  $.ajax( {url: "ajax.php?function=del&id=" + itemid + "&pid=" + pid,
    success: function(response){
      $("#message").html("<p>" + lang.deleted_from_cart + "</p>");
      getcart();
    },
    datatype: "html"
  });
}

function showhideRegLogin(){
  $('#reg, #login').toggle();
  return false;
}

// document load
$(document).ready(function(){
  getcart();
  setupValidation();
});




